﻿using Core.DataAccess.Model.Project.Logs;
using Core.DataAccess.Model.ProjectLogs;
using Microsoft.Extensions.Logging;
using System;
using Microsoft.EntityFrameworkCore.Design;

namespace Core.DataAccess.Model
{
    public class EFLogger : ILogger
    {

        public static LoggerFactory GetLoggerFactory()
        {
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(new EFLoggerProvider());
            return loggerFactory;
        }

        private readonly string categoryName;

        public EFLogger(string categoryName) => this.categoryName = categoryName;

        public bool IsEnabled(LogLevel logLevel) => true;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {

            if (logLevel == LogLevel.Information)
            {
                switch (categoryName)
                {
                    case "Microsoft.EntityFrameworkCore.Database.Command":

                        //using (var context = new ProjectLogsContext())
                        //{
                        //    context.Logger.Add(new Logger
                        //    {
                        //        Template = "sqlserver",
                        //        Content = formatter(state, exception)
                        //    });
                        //    context.SaveChanges();
                        //}

                        break;
                }   
            }
        }

        public IDisposable BeginScope<TState>(TState state) => null;
    }

    public class EFLoggerProvider : ILoggerProvider
    {
        public ILogger CreateLogger(string categoryName) => new EFLogger(categoryName);
        public void Dispose() { }
    }

}
